<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="3">
        <el-input
          class="filterInput"
          clearable
          placeholder="请输入分类名称"
          v-model="filterCategoryName"
        >
        </el-input>
        <el-tree
          :highlight-current="true"
          ref="tree"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="selectedCategory"
        ></el-tree
      ></el-col>
      <el-col :span="21">
        <el-form :inline="true" ref="queryForm" :model="query">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="16">
              <!-- 检索条件 start -->
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="query.name"
                  placeholder="请输入昵称"
                ></el-input>
              </el-form-item>
              <!-- 检索条件 end -->

              <el-form-item>
                <el-button icon="el-icon-search" @click="querySearchForm"
                  >搜索</el-button
                >
                <el-button icon="el-icon-refresh" @click="resetSearchForm"
                  >重置</el-button
                >
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-tag class="categoryName"
                >选中分类：{{ selectedCategoryName }}</el-tag
              >
            </el-col>
            <el-col :span="2" class="table-tools">
              <el-button
                @click="openDialog()"
                icon="el-icon-plus"
                :disabled="selectedCategoryId == null"
                v-if="hasPermission(permission.save)"
                >{{ "添加" + dialogTitle }}</el-button
              >
            </el-col>
          </el-row>
        </el-form>

        <el-table
          stripe
          border
          :data="tableData"
          style="width: 100%"
          :height="maxTableHeight"
        >
          <!-- 表格属性 start -->
          <el-table-column prop="name" label="属性名称" width="180" />
          <el-table-column
            prop="options"
            label="可选项"
            :show-overflow-tooltip="true"
          >
            <template
              slot-scope="scope"
              v-if="scope.row.optionList != '' && scope.row.optionList != null"
            >
              <el-tag
                class="options-tag"
                type="info"
                v-for="(option, index) in scope.row.optionList"
                :key="index"
              >
                {{ option.attrValue }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 表格属性 end -->

          <el-table-column
            fixed="right"
            label="操作"
            width="170"
            v-if="hasAnyPermission()"
          >
            <template slot-scope="scope">
              <div class="btnOperateList">
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-top"
                  :disabled="scope.$index == 0"
                  @click="attrSortUp(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-bottom"
                  :disabled="scope.$index == tableData.length - 1"
                  @click="attrSortDown(scope.$index)"
                  v-if="hasPermission(permission.update)"
                ></el-button>

                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-edit"
                  @click="openDialog(scope.row)"
                  v-if="hasPermission(permission.update)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="text"
                  size="medium"
                  icon="el-icon-delete"
                  @click="deleteRow(scope.row)"
                  v-if="hasPermission(permission.delete)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <Update ref="updateDialog" :dialogTitle="dialogTitle"></Update>
  </div>
</template>

<script>
import { mapState } from "vuex";
import listMixins from "@/views/base/listMixins";

// 请求接口 start
import Update from "@/views/product/saleAttr/update";
import productApi from "@/api/productApi";
// 请求接口 end

export default {
  // 组件名称 start
  name: "productSaleAttr",
  // 组件名称 start

  components: {
    Update,
  },
  mixins: [listMixins],
  data() {
    return {
      // 分类树信息
      treeProps: {
        children: "children",
        label: "name",
      },
      filterCategoryName: "",

      // 选中的分类ID
      selectedCategoryId: null,
      selectedCategoryName: "",

      // 分类列表数据
      treeData: [],

      // 数据 start
      dialogTitle: "销售属性",
      permission: {
        save: "product:saleAttr:save",
        update: "product:saleAttr:update",
        delete: "product:saleAttr:delete",
      },
      query: {
        name: "",
      },
      // 数据 end
    };
  },
  created() {
    this.remoteCategoryTreeList();
  },
  methods: {
    attrSortUp(index) {
      if (index > 0) {
        console.log(this.tableData[index - 1].id);
        productApi.saleAttr
          .swapSort(this.tableData[index - 1].id, this.tableData[index].id)
          .then((res) => {
            this.resetSearchForm();
          })
          .catch((error) => {});
      }
    },
    attrSortDown(index) {
      if (index < this.tableData.length - 1) {
        productApi.saleAttr
          .swapSort(this.tableData[index].id, this.tableData[index + 1].id)
          .then((res) => {
            this.resetSearchForm();
          })
          .catch((error) => {});
      }
    },
    // 分类树
    remoteCategoryTreeList() {
      productApi.category
        .treeList()
        .then((res) => {
          this.treeData = res.data;
          this.$nextTick(() => {
            this.expandAll();
          });
        })
        .catch((error) => {});
    },
    // 全部展开
    expandAll() {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].expanded = true;
      }
    },
    // 商品分类过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 选中分类
    selectedCategory(data, node, tree) {
      // 获取当前节点所有父级节点
      var parentNodeArr = [];
      var parentNameArr = [];
      this.getParentAll(parentNodeArr, node);
      parentNodeArr.forEach((node, index, arr) => {
        parentNameArr.push(node.data.name);
      });
      parentNameArr.push(data.name);

      // 拼接字符串
      this.selectedCategoryName = parentNameArr.join(" -> ");
      this.selectedCategoryId = data.id;
      this.querySearchForm();
    },
    // 获取当前节点所有父级节点
    getParentAll(parentNodeArr, node) {
      if (node) {
        // 节点的第一个父级
        var parentNode = node.parent;
        // level为节点的层级 level=1 为顶级节点
        for (var j = 0, lv = node.level; j < lv; j++) {
          if (parentNode.level > 0) {
            // 将所有父级节点放入集合中
            parentNodeArr.push(parentNode);
          }
          // 继续获取父级节点的父级节点
          parentNode = parentNode.parent;
        }

        if (parentNodeArr.length > 1) {
          // 如果集合长度>1 则将数组进行倒叙.reverse() 其是就是将所有节点按照 从 顶级节点 依次往下排
          parentNodeArr.reverse();
        }
      }
    },
    beforeOpen() {
      this.$refs["updateDialog"].setMeta({
        categoryId: this.selectedCategoryId,
      });
    },
    remoteTableData() {
      // 分页请求 start
      if (this.selectedCategoryId != null) {
        productApi.saleAttr
          .list(this.selectedCategoryId)
          .then((res) => {
            this.updateNoPageTableData(res.data);
          });
      }

      // 分页请求 end
    },
    // 删除
    deleteRow(row) {
      this.$confirm("确认删除角色 [ " + row.name + " ] ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          productApi.saleAttr
            .delete(row.id)
            .then((res) => {
              this.resetSearchForm();
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
  computed: mapState({
    user: (state) => state.user.userInfo,
  }),
};
</script>
<style lang="less" scoped>
.options-tag {
  margin-right: 8px;
  height: 36px;
  line-height: 36px;
}
.categoryName {
  margin-top: 5px;
}
.btnOperateList {
  .el-button {
    margin-right: 10px;
  }
  .el-button:last-child {
    margin-right: 0px;
  }
}
</style>